from django.db import models
from django.core.validators import MinValueValidator
from decimal import Decimal


class Category(models.Model):
    """产品分类模型"""
    name = models.CharField('分类名称', max_length=100)
    description = models.TextField('分类描述', blank=True)
    parent = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        verbose_name='父分类',
        related_name='children'
    )
    is_active = models.BooleanField('是否激活', default=True)
    sort_order = models.IntegerField('排序', default=0)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '产品分类'
        verbose_name_plural = '产品分类管理'
        ordering = ['sort_order', 'name']

    def __str__(self):
        return self.name


class Brand(models.Model):
    """品牌模型"""
    name = models.CharField('品牌名称', max_length=100)
    logo = models.ImageField('品牌LOGO', upload_to='brands/', blank=True, null=True)
    description = models.TextField('品牌描述', blank=True)
    website = models.URLField('官方网站', blank=True)
    is_featured = models.BooleanField('精选品牌', default=False)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '品牌'
        verbose_name_plural = '品牌管理'
        ordering = ['name']

    def __str__(self):
        return self.name


class Product(models.Model):
    """产品模型"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('active', '在售'),
        ('inactive', '下架'),
        ('out_of_stock', '缺货'),
    ]

    name = models.CharField('产品名称', max_length=200)
    slug = models.SlugField('产品别名', unique=True)
    description = models.TextField('产品描述')
    short_description = models.CharField('简短描述', max_length=255, blank=True)

    category = models.ForeignKey(
        Category,
        on_delete=models.CASCADE,
        verbose_name='分类',
        related_name='products'
    )
    brand = models.ForeignKey(
        Brand,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name='品牌',
        related_name='products'
    )

    price = models.DecimalField(
        '价格',
        max_digits=10,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0.01'))]
    )
    original_price = models.DecimalField(
        '原价',
        max_digits=10,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(Decimal('0.01'))]
    )

    stock_quantity = models.PositiveIntegerField('库存数量', default=0)
    min_stock_level = models.PositiveIntegerField('最低库存', default=5)

    image = models.ImageField('产品图片', upload_to='products/', blank=True, null=True)

    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='draft')
    is_featured = models.BooleanField('精选产品', default=False)
    is_digital = models.BooleanField('数字产品', default=False)

    weight = models.DecimalField('重量(kg)', max_digits=8, decimal_places=3, null=True, blank=True)
    dimensions = models.CharField('尺寸', max_length=100, blank=True)

    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '产品'
        verbose_name_plural = '产品管理'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', 'is_featured']),
            models.Index(fields=['category', 'status']),
        ]

    def __str__(self):
        return self.name

    @property
    def discount_percentage(self):
        """计算折扣百分比"""
        if self.original_price and self.original_price > self.price:
            return round((1 - self.price / self.original_price) * 100, 1)
        return 0

    @property
    def is_low_stock(self):
        """是否低库存"""
        return self.stock_quantity <= self.min_stock_level


class ProductImage(models.Model):
    """产品图片模型"""
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='images',
        verbose_name='产品'
    )
    image = models.ImageField('图片', upload_to='products/gallery/')
    alt_text = models.CharField('替代文本', max_length=200, blank=True)
    is_primary = models.BooleanField('主图', default=False)
    sort_order = models.PositiveIntegerField('排序', default=0)

    class Meta:
        verbose_name = '产品图片'
        verbose_name_plural = '产品图片管理'
        ordering = ['sort_order']

    def __str__(self):
        return f"{self.product.name} - 图片{self.id}"
